package zte.wb;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class TestZookeeper {
	private volatile static ZooKeeper zk ; 
	private static String node = "/testnode";
	public static void main(String[] args) throws Exception {
		  zk = new ZooKeeper("127.0.0.1:2181", 300000,
				new DemoWatcher());// 连接zk server
		Stat stat = zk.exists(node, new DemoWatcher());// 检测/app1是否存在
		// 获取节点的值
		byte[] b = zk.getData(node, false, stat);
		System.out.println(new String(b));
		
		//监听节点变化
		
		   while (true) {
	            TimeUnit.SECONDS.sleep(5);
	        }
	}

	static class DemoWatcher implements Watcher {
		public void process(WatchedEvent event) {
			System.out.println("----------->");
			System.out.println("path:" + event.getPath());
			System.out.println("type:" + event.getType());
			System.out.println("stat:" + event.getState());
			System.out.println("<-----------");
			try {
				zk.exists(node, new DemoWatcher());
			} catch (KeeperException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
